<template>
  <div class="route-share">
    <el-page-header @back="goBack">
      <template #content>
        <span class="text-large font-600 mr-3">分享的路线</span>
      </template>
    </el-page-header>

    <div v-loading="loading" class="share-content">
      <el-card v-if="routePlan" shadow="hover">
        <template #header>
          <div class="card-header">
            <h2>{{ routePlan.start_attraction?.name || '路线规划' }}</h2>
            <el-tag type="success" v-if="routePlan.is_shared">已分享</el-tag>
          </div>
        </template>

        <!-- 统计信息 -->
        <div class="statistics-section" v-if="routePlan.view_count !== undefined || routePlan.share_count !== undefined || routePlan.use_count !== undefined">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-icon view">
                  <el-icon><View /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-label">浏览量</div>
                  <div class="stat-value">{{ routePlan.view_count || 0 }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-icon share">
                  <el-icon><Share /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-label">分享次数</div>
                  <div class="stat-value">{{ routePlan.share_count || 0 }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-icon use">
                  <el-icon><MapLocation /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-label">使用次数</div>
                  <div class="stat-value">{{ routePlan.use_count || 0 }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 路线摘要 -->
        <div class="route-summary">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="起始景点">
              {{ routePlan.start_attraction?.name || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="预算">
              ¥{{ routePlan.budget }}
            </el-descriptions-item>
            <el-descriptions-item label="总费用">
              ¥{{ routePlan.total_cost }}
            </el-descriptions-item>
            <el-descriptions-item label="总距离">
              {{ routePlan.total_distance }} 公里
            </el-descriptions-item>
            <el-descriptions-item label="景点数量">
              {{ routePlan.optimal_route?.route?.length || 0 }} 个
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDate(routePlan.created_at) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 路线详情 -->
        <el-divider>路线详情</el-divider>
        <div class="route-details">
          <el-timeline>
            <el-timeline-item
              v-for="(detail, index) in routePlan.optimal_route?.details"
              :key="index"
              :timestamp="`第${detail.order}站`"
              placement="top"
            >
              <el-card>
                <h4>{{ detail.attraction_name }}</h4>
                <p v-if="detail.address">地址：{{ detail.address }}</p>
                <p>门票：¥{{ detail.ticket_price }}</p>
                <p v-if="detail.visit_time">建议游览时间：{{ detail.visit_time }}分钟</p>
                <div v-if="detail.from_previous" class="transport-info">
                  <el-tag size="small">距离：{{ detail.from_previous.distance }}公里</el-tag>
                  <el-tag size="small" type="success">费用：¥{{ detail.from_previous.cost }}</el-tag>
                  <el-tag size="small" type="info">时间：{{ detail.from_previous.time }}分钟</el-tag>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button
            v-if="isAuthenticated"
            type="primary"
            size="large"
            :icon="MapLocation"
            @click="planSameRoute"
          >
            使用此路线规划
          </el-button>
          <el-button
            v-if="isAuthenticated && routePlan.id"
            :type="routePlan.is_favorited ? 'warning' : 'default'"
            size="large"
            :icon="Star"
            :loading="favoriting"
            @click="toggleFavorite"
          >
            {{ routePlan.is_favorited ? '已收藏' : '收藏路线' }}
          </el-button>
          <el-button
            v-if="isAuthenticated && routePlan.id"
            type="success"
            size="large"
            :icon="Share"
            @click="shareAgain"
          >
            再次分享
          </el-button>
          <el-button
            v-if="routePlan.share_code"
            type="warning"
            size="large"
            :icon="Picture"
            @click="openQRCodeDialog"
          >
            分享二维码
          </el-button>
          <el-button
            v-if="routePlan.share_code"
            type="info"
            size="large"
            :icon="CopyDocument"
            @click="copyShareLink"
          >
            复制链接
          </el-button>
        </div>
      </el-card>

      <el-empty v-else description="路线不存在或已取消分享" :image-size="200">
        <el-button type="primary" @click="goBack">返回首页</el-button>
      </el-empty>
    </div>

    <!-- 地图展示 -->
    <el-card v-if="routePlan && routePlan.optimal_route?.details" shadow="hover" style="margin-top: 20px;">
      <template #header>
        <span>路线地图</span>
      </template>
      <div id="route-share-map" style="width: 100%; height: 500px;"></div>
    </el-card>

    <!-- 二维码对话框 -->
    <el-dialog
      v-model="showQRCodeDialog"
      title="分享二维码"
      width="400px"
      center
    >
      <div style="text-align: center; padding: 20px;">
        <div v-if="shareQRCodeUrl" style="margin-bottom: 20px;">
          <img :src="shareQRCodeUrl" alt="分享二维码" style="max-width: 100%; border: 1px solid #ddd; border-radius: 8px;" />
        </div>
        <div v-else style="padding: 40px;">
          <el-icon class="is-loading" style="font-size: 40px;"><Loading /></el-icon>
          <p style="margin-top: 10px; color: #909399;">正在生成二维码...</p>
        </div>
        <div v-if="shareUrl" style="margin-top: 20px;">
          <el-input
            :model-value="shareUrl"
            readonly
            style="margin-bottom: 10px;"
          >
            <template #append>
              <el-button :icon="CopyDocument" @click="copyShareLinkFromDialog">复制</el-button>
            </template>
          </el-input>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { MapLocation, Share, View, Picture, CopyDocument, Loading, Star } from '@element-plus/icons-vue'
import TravelAPI from '../api/travel'
import { AMapUtil } from '../utils/amap'
import logger from '../utils/logger'

export default {
  name: 'RouteShare',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const loading = ref(false)
    const routePlan = ref(null)
    const amapUtil = ref(null)
    const showQRCodeDialog = ref(false)
    const shareQRCodeUrl = ref('')
    const shareUrl = ref('')
    const favoriting = ref(false)

    const isAuthenticated = computed(() => store.getters.isAuthenticated)

    const formatDate = (date) => {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
    }

    const fetchRouteByShareCode = async () => {
      const shareCode = route.params.code || route.query.code
      if (!shareCode) {
        ElMessage.error('分享码不存在')
        router.push('/')
        return
      }

      loading.value = true
      try {
        const data = await TravelAPI.getRouteByShareCode(shareCode)
        routePlan.value = data
        
        // 绘制地图
        if (data.optimal_route?.details) {
          await drawRouteMap(data.optimal_route.details)
        }
      } catch (error) {
        logger.error('获取分享路线失败:', error)
        let errorMessage = '获取路线失败'
        if (error.response) {
          const status = error.response.status
          if (status === 404) {
            errorMessage = '路线不存在或已取消分享'
          } else if (status === 500) {
            errorMessage = '服务器错误，请稍后重试'
          } else if (error.response.data?.error) {
            errorMessage = error.response.data.error
          } else if (error.response.data?.detail) {
            errorMessage = error.response.data.detail
          }
        } else if (error.message) {
          if (error.message.includes('timeout')) {
            errorMessage = '请求超时，请检查网络连接'
          } else if (error.message.includes('Network Error')) {
            errorMessage = '网络错误，请检查网络连接'
          }
        }
        ElMessage.error(errorMessage)
        setTimeout(() => {
          router.push('/')
        }, 2000)
      } finally {
        loading.value = false
      }
    }

    const drawRouteMap = async (details) => {
      await new Promise(resolve => setTimeout(resolve, 300))

      try {
        const apiKey = process.env.VUE_APP_AMAP_KEY || ''
        if (!apiKey || apiKey === 'your_amap_api_key') {
          ElMessage.warning('高德地图API Key未配置，地图功能不可用')
          return
        }

        if (!amapUtil.value) {
          amapUtil.value = new AMapUtil(apiKey)
        }

        if (amapUtil.value.map) {
          amapUtil.value.map.destroy()
          amapUtil.value.map = null
        }

        // 计算中心点
        const centerLng = details.reduce((sum, d) => sum + parseFloat(d.longitude), 0) / details.length
        const centerLat = details.reduce((sum, d) => sum + parseFloat(d.latitude), 0) / details.length

        await amapUtil.value.initMap('route-share-map', {
          center: [centerLng, centerLat],
          zoom: 12
        })

        // 准备标记点数据
        const markers = details.map(detail => ({
          lng: parseFloat(detail.longitude),
          lat: parseFloat(detail.latitude),
          title: detail.attraction_name,
          info: `
            <div style="padding: 10px;">
              <h3 style="margin: 0 0 10px 0; color: #409eff;">${detail.attraction_name}</h3>
              <p style="margin: 5px 0;"><strong>门票：</strong>¥${detail.ticket_price}</p>
              ${detail.visit_time ? `<p style="margin: 5px 0;"><strong>游览时间：</strong>${detail.visit_time}分钟</p>` : ''}
            </div>
          `
        }))

        // 准备路线数据
        const path = details.map(detail => [parseFloat(detail.longitude), parseFloat(detail.latitude)])

        amapUtil.value.addMarkers(markers)
        amapUtil.value.drawRoute(path)
      } catch (error) {
        logger.error('地图绘制失败:', error)
        ElMessage.error('地图加载失败')
      }
    }

    const planSameRoute = async () => {
      if (!routePlan.value) return
      
      // 增加使用次数
      if (routePlan.value.id) {
        try {
          const response = await TravelAPI.incrementRouteUse(routePlan.value.id)
          // 更新本地数据
          if (response && response.use_count !== undefined) {
            routePlan.value.use_count = response.use_count
          } else {
            routePlan.value.use_count = (routePlan.value.use_count || 0) + 1
          }
          ElMessage.success('已记录使用，正在跳转到路线规划页面...')
        } catch (error) {
          logger.error('更新使用次数失败:', error)
          // 即使更新失败也继续跳转
        }
      }
      
      router.push({
        path: '/route-plan',
        query: {
          start_attraction_id: routePlan.value.start_attraction?.id,
          must_visit: routePlan.value.must_visit_attractions?.join(',') || '',
          budget: routePlan.value.budget
        }
      })
    }

    const toggleFavorite = async () => {
      if (!routePlan.value?.id) {
        ElMessage.warning('路线ID不存在')
        return
      }

      favoriting.value = true
      try {
        const isFavorite = routePlan.value.is_favorited
        await TravelAPI.toggleRouteFavorite(routePlan.value.id, isFavorite)
        
        // 更新本地状态
        routePlan.value.is_favorited = !isFavorite
        routePlan.value.favorites_count = (routePlan.value.favorites_count || 0) + (isFavorite ? -1 : 1)
        
        ElMessage.success(isFavorite ? '已取消收藏' : '收藏成功')
      } catch (error) {
        logger.error('收藏操作失败:', error)
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '收藏操作失败' })
        })
      } finally {
        favoriting.value = false
      }
    }

    const shareAgain = async () => {
      if (!routePlan.value?.id) {
        ElMessage.warning('路线ID不存在')
        return
      }

      try {
        const response = await TravelAPI.shareRoute(routePlan.value.id)
        routePlan.value.is_shared = true
        routePlan.value.share_code = response.share_code
        routePlan.value.share_count = (routePlan.value.share_count || 0) + 1
        ElMessage.success('分享成功！分享链接已生成')
      } catch (error) {
        logger.error('分享失败:', error)
        let errorMessage = '分享失败'
        if (error.response?.data?.error) {
          errorMessage = error.response.data.error
        } else if (error.response?.data?.detail) {
          errorMessage = error.response.data.detail
        } else if (error.message) {
          errorMessage = error.message
        }
        ElMessage.error(errorMessage)
      }
    }

    const generateQRCode = (url) => {
      // 使用在线API生成二维码（无需安装额外依赖）
      const encodedUrl = encodeURIComponent(url)
      return `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodedUrl}`
    }

    const openQRCodeDialog = () => {
      if (!routePlan.value?.share_code) {
        ElMessage.warning('分享码不存在')
        return
      }

      shareUrl.value = `${window.location.origin}/route-share/${routePlan.value.share_code}`
      shareQRCodeUrl.value = generateQRCode(shareUrl.value)
      showQRCodeDialog.value = true
    }

    const copyShareLink = () => {
      if (!routePlan.value?.share_code) {
        ElMessage.warning('分享码不存在')
        return
      }

      const url = `${window.location.origin}/route-share/${routePlan.value.share_code}`
      
      // 优先使用现代 Clipboard API
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(url).then(() => {
          ElMessage.success('分享链接已复制到剪贴板')
        }).catch(() => {
          fallbackCopyToClipboard(url)
        })
      } else {
        fallbackCopyToClipboard(url)
      }
    }

    const copyShareLinkFromDialog = () => {
      if (!shareUrl.value) return
      
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(shareUrl.value).then(() => {
          ElMessage.success('分享链接已复制到剪贴板')
        }).catch(() => {
          fallbackCopyToClipboard(shareUrl.value)
        })
      } else {
        fallbackCopyToClipboard(shareUrl.value)
      }
    }

    const fallbackCopyToClipboard = (text) => {
      try {
        const textArea = document.createElement('textarea')
        textArea.value = text
        textArea.style.position = 'fixed'
        textArea.style.left = '-999999px'
        textArea.style.top = '-999999px'
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        const successful = document.execCommand('copy')
        document.body.removeChild(textArea)
        
        if (successful) {
          ElMessage.success('分享链接已复制到剪贴板')
        } else {
          ElMessage.info('请手动复制链接: ' + text)
        }
      } catch (error) {
        logger.error('复制失败:', error)
        ElMessage.info('请手动复制链接: ' + text)
      }
    }

    const goBack = () => {
      router.push('/')
    }

    onMounted(() => {
      fetchRouteByShareCode()
    })

    return {
      loading,
      routePlan,
      isAuthenticated,
      formatDate,
      planSameRoute,
      toggleFavorite,
      favoriting,
      shareAgain,
      goBack,
      openQRCodeDialog,
      copyShareLink,
      copyShareLinkFromDialog,
      showQRCodeDialog,
      shareQRCodeUrl,
      shareUrl,
      MapLocation,
      Share,
      View,
      Picture,
      CopyDocument,
      Loading,
      Star
    }
  }
}
</script>

<style scoped>
.route-share {
  /* 南昌旅游特色：天空蓝渐变背景 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  min-height: 100vh;
  padding: 20px;
  animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.route-share {
  max-width: 1200px;
  margin: 0 auto;
}

.share-content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.route-summary {
  margin-bottom: 20px;
}

.route-details {
  margin-top: 20px;
}

.transport-info {
  margin-top: 10px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  justify-content: center;
}

.statistics-section {
  margin-bottom: 20px;
  padding: 20px;
  /* 南昌红到滕王阁金渐变 */
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  border-radius: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  color: white;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  margin-right: 16px;
  font-size: 24px;
}

.stat-icon.view {
  /* 赣江蓝半透明 */
  background: rgba(30, 136, 229, 0.3);
}

.stat-icon.share {
  /* 自然绿半透明 */
  background: rgba(76, 175, 80, 0.3);
}

.stat-icon.use {
  /* 南昌红半透明 */
  background: rgba(200, 16, 46, 0.3);
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 5px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: white;
}
</style>






